package com.unicampmaps;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageButton;

public class FoursquareVenueFetcher extends
		AsyncTask<String, Void, FoursquareVenueData> {

	private static final String VENUES_API = "https://api.foursquare.com/v2/venues/";
	private static final String TIPS_URI = "/tips?sort=recent";
	private static final String PHOTOS_URI = "/photos?";
	private static final String CLIENT_ID = "3FD4BRBC3GB1XTIX0MCUOOSJVJ4NXTE5QBOK15AZMKI2IKGE";
	private static final String CLIENT_SECRET = "QCND0RAPJFE25PRSDUTR3RJVXFJTLZ3IHI15XOPIY2TKJ4M0";
	private static final String API_VERSION = "20130618";
	private static final String PHOTO_REDIMENSION = "cap300";
	public final static int TIMEOUT = 10;

	private String tips;
	private String photos;
	private String venueId;
	private DetailsActivity detailsActiviy;
	private String cachePath;

	public FoursquareVenueFetcher(String venueId,
			DetailsActivity detailsActivity, String cachePath) {
		this.venueId = venueId;
		this.tips = VENUES_API + this.venueId + TIPS_URI + "&client_id="
				+ CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&v="
				+ API_VERSION;
		this.photos = VENUES_API + this.venueId + PHOTOS_URI + "client_id="
				+ CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&v="
				+ API_VERSION;
		this.detailsActiviy = detailsActivity;
		this.cachePath=cachePath;
	}

	@Override
	protected void onPostExecute(FoursquareVenueData o) {
		detailsActiviy.fillData(o);
	}

	public String getTips() {
		return tips;
	}

	public String getPhotos() {
		return photos;
	}

	@Override
	protected FoursquareVenueData doInBackground(String... urls) {
		FoursquareVenueData fvd = new FoursquareVenueData();
		fvd.tips = this.getTips(urls[0]);
		fvd.photos = this.getPhotos(urls[1]);
		return fvd;
	}

	private DefaultHttpClient createHttpClient() {
		final SchemeRegistry supportedSchemes = new SchemeRegistry();

		supportedSchemes.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		supportedSchemes.register(new Scheme("https", SSLSocketFactory
				.getSocketFactory(), 443));

		final HttpParams params = new BasicHttpParams();

		HttpConnectionParams.setConnectionTimeout(params,
				FoursquareVenueFetcher.TIMEOUT * 1000);
		HttpConnectionParams.setSoTimeout(params,
				FoursquareVenueFetcher.TIMEOUT * 1000);
		HttpConnectionParams.setSocketBufferSize(params, 8192);

		HttpClientParams.setRedirecting(params, false);

		final ClientConnectionManager com = new ThreadSafeClientConnManager(
				params, supportedSchemes);

		return new DefaultHttpClient(com, params);
	}

	private String getUrlJSON(String url) {
		HttpGet httpGet = new HttpGet(url);

		DefaultHttpClient httpClient = createHttpClient();

		HttpResponse httpResponse;
		try {
			httpResponse = httpClient.execute(httpGet);
			String response = EntityUtils.toString(httpResponse.getEntity());

			return response;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	private List<String> getTips(String url) {
		String json = getUrlJSON(url);
		List<String> list = new ArrayList<String>();

		try {
			JSONArray tips = (JSONArray) ((JSONObject) ((JSONObject) new JSONObject(
					json).get("response")).get("tips")).get("items");

			// gets tips from result JSON
			for (int i = 0; !tips.isNull(i); i++) {
				String tip = ((JSONObject) tips.get(i)).getString("text");
				list.add(tip);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return list;
	}

	private List<Bitmap> getPhotos(String url) {
		String json = getUrlJSON(url);
		List<Bitmap> list = new ArrayList<Bitmap>();

		try {
			JSONArray photos = (JSONArray) ((JSONObject) ((JSONObject) new JSONObject(
					json).get("response")).get("photos")).get("items");

			// gets the first 3 photos
			for (int i = 0; !photos.isNull(i) && i < photos.length(); i++) {
				String prefix = ((JSONObject) photos.get(i))
						.getString("prefix");
				String suffix = ((JSONObject) photos.get(i))
						.getString("suffix");
				String path = prefix + PHOTO_REDIMENSION + suffix;
				list.add(getImage(cachePath,path));
				System.out.println("URL DE UMA FOTO: " + path);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return list;
	}

	private Bitmap getImage(String cachePath,String urlToImage) {
		URL url;
		InputStream in;
		BufferedOutputStream out = null;
		BufferedInputStream buf = null;
		Bitmap image = null;
		String[] splitted = urlToImage.split("/");
		
		String imgName=splitted[splitted.length-1];
		
		File file= new File(cachePath,imgName);
		
		if(!file.exists()){
			try {
				url = new URL(urlToImage);
				in = url.openStream();
				out= new BufferedOutputStream(new FileOutputStream(file));
				
				byte[] buffer= new byte[1024];
				int bytesRead=-1;
				while((bytesRead=in.read(buffer))>0){
					out.write(buffer,0,bytesRead);
				}
			
				in.close();
				out.close();
				buf.close();
				
			} catch (Exception e) {
				Log.e("Error reading file", e.toString());
			}
		}
		
		try {
			in=new FileInputStream(file);
			buf = new BufferedInputStream(in);
			image = BitmapFactory.decodeStream(buf);
			return image;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		
		return image;
	}

}
